const app = getApp();
const regeneratorRuntime  =require("../../utils/regeneratorRuntime.js")
const promisify = require('../../utils/promisify.js');
// const request = promisify(wx.request);

import { $wuxActionSheet } from '../../dist/index'
const wxGetLocation = promisify(wx.getLocation);
const getImageInfo = promisify(wx.getImageInfo);
import { $wuxDialog } from '../../dist/index'
// const uploadFile = promisify(wx.uploadFile);


Page({

  data: {
    statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],
    isIphoneX: app.globalData.isIphoneX,
    isIphone: app.globalData.isIphone,
    store_detail: {},
    openShelfCamera: false,

    getData: function (e) {
      console.log(e)
    },
    // 拍照货架场景
    shelf_type_array: ['货架', '冰柜', '堆头', '其他'],
    pack_type_array: ['饮料', '调味品', '啤酒', '其他'],
    errImgArr: [],
    loadingtime: [],

    currentShelfType: '',
    currentPackType: '',

    isStoreUnfold: false,
    autoAddTimer: null,

    // canvas默认尺寸
    canvas_size: {
      width: 720,
      height: 1080
    },
    // 自定义相机拍照类型 （拍完上传，保存到相册）
    custom_camera_type: '',
    // 自定义相机拍照后的图片
    camera_image: null
  },

  onLoad: async function (options) {
    wx.setNavigationBarTitle({
      title: '陈列拍照'
    })
    this.setData({
      isIphoneX: app.globalData.isIphoneX,
      // baseUrl
    })
    app.globalData.store_detail['display_photograph'] = {}
    app.globalData.store_detail['display_photograph']['scene_list'] = []
    app.globalData.store_detail['display_photograph']['shelf_type_array'] = ['货架', '冰柜', '堆头', '其他']
    app.globalData.store_detail['display_photograph']['pack_type_array'] = ['饮料', '调味品', '啤酒', '其他']


    await this.getLocation()
  },

  // 获取GPS定位
  getLocation: async function () {
    try {
      const resp = await wxGetLocation({
        type: 'wgs84',
      })
      const { latitude, longitude } = resp
      this.setData({ latitude, longitude })
    } catch (e) {
      console.log(e)
    }
  },

  // 新增场景
  onAddScene: function (e) {
    var that = this
    console.log(e)
    if (app.globalData.store_detail['display_photograph']['scene_list'] != undefined && app.globalData.store_detail['display_photograph']['scene_list'].length == 5) {
      wx.showModal({
        content: '至多添加5个陈列',
        showCancel: false,
      })
    }
    
    var scene_id = app.globalData.store_detail['display_photograph']['scene_list'].length+1
    var my_obj = { 'scene_id': scene_id, 'img_list': [], 'shelf_type': null, 'pack_type': null }
    app.globalData.store_detail['display_photograph']['scene_list'].push(my_obj)
    that.setData({
      display_photograph: app.globalData.store_detail['display_photograph']
    })
    console.log(that.data.display_photograph)

    var picker_choose3 = {
      'currentTarget': {
        'dataset': {
          'index1': app.globalData.store_detail['display_photograph']['scene_list'].length - 1, 'sceneid': scene_id, 'type': 'shelf_type'
        }
      },
      'detail': {
        'value': 0
      }
    }
    var picker_choose4 = {
      'currentTarget': {
        'dataset': {
          'index1': app.globalData.store_detail['display_photograph']['scene_list'].length - 1, 'sceneid': scene_id, 'type': 'pack_type'
        }
      },
      'detail': {
        'value': 0
      }
    }

  },

  bindScenePickerChange: function (e) {
    var index1 = e.currentTarget.dataset.index1
    var type = e.currentTarget.dataset.type

    if (type === "shelf_type") {
      app.globalData.store_detail['display_photograph']['scene_list'][index1][type] = app.globalData.store_detail['display_photograph'].shelf_type_array[parseInt(e.detail.value)]
    }
    else if (type === 'pack_type') {
      app.globalData.store_detail['display_photograph']['scene_list'][index1][type] = app.globalData.store_detail['display_photograph'].pack_type_array[parseInt(e.detail.value)]
    }
    this.setData({
      display_photograph: app.globalData.store_detail['display_photograph']
    })
  },

  // 删除场景
  onDeleteScene: function (e) {
    const that = this;
    $wuxDialog().open({
      title: '确定删除货架？',
      maskClosable: false,
      prefixCls: 'xdt',
      // content: '弹窗内容，告知当前状态、信息和解决方法，描述文字尽量控制在三行内',
      buttons: [
          {
              text: '取消',
          },
          {
              text: '确定',
              type: 'primary',
              onTap(event) {
                var sceneid = e.currentTarget.dataset.sceneid
                console.log(sceneid)
                var index1 = e.currentTarget.dataset.index1

                var scene_list = app.globalData.store_detail['display_photograph']['scene_list']
                scene_list.splice(index1, 1)
                app.globalData.store_detail['display_photograph']['scene_list'] = scene_list
                that.setData({
                  display_photograph: app.globalData.store_detail['display_photograph']
                })
                console.log(that.data.display_photograph)
              },
          },
      ],
    })
  },

  addPhoto(e) {
    console.log(e)
    const that = this
    const sceneItem = e.currentTarget.dataset.sceneitem
    const scene_id = e.currentTarget.dataset.sceneid
    this.data.currentSceneId = scene_id
    if (sceneItem['shelf_type'] == null || sceneItem['pack_type'] == null) {
      wx.showToast({
        title: '请先选择【陈列方式】及【商品种类】',
        icon: 'none'
      })
      return
    }

    const hide = $wuxActionSheet().showSheet({
      theme: 'wx',
      titleText: '请竖直手机正对货架拍摄，请勿横拍',
      buttons: [{
              text: '拍摄照片并上传'
          },
          {
              text: '拍摄照片至相册'
          },
          {
              text: '从相册选择照片'
          },
      ],
      async buttonClicked(index, item) {
        if(index === 0) {
          that.controlShelfCamera({ type: 'upload' })
        } else if (index === 1) {
          that.controlShelfCamera({ type: 'save' })
        } else if (index === 2) {
          that.chooseImageFromAlbum({ sceneItem, scene_id, that, hide })
        }
        return true
      },
    })
  },


  // 打开模拟的相机界面
  controlShelfCamera({ type }) {
    this.setData({
      openShelfCamera: true,
    })
    this.data.canTakePhoto = true
    this.data.custom_camera_type = type
    // this.visit_camera()
  },

  // 关闭相机画面
  closeShelfCamera() {
    this.setData({
      openShelfCamera: false,
      camera_image: null
    })
  },

  //
  visit_camera: function () {
    const { currentSceneId:scene_id, canTakePhoto, custom_camera_type } = this.data
    if(!canTakePhoto) {
      return
    }
    const that = this
    const ctx = wx.createCameraContext()
    const { isIphone } = app.globalData

    ctx.takePhoto({
      quality: "high",
    // wx.chooseImage({
    //   count: 1,
    //   sizeType: ['original'],
    //   sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempImagePath
        // var tempFilePaths = res.tempFilePaths[0]
        // 自定义拍照预览
        that.setData({ camera_image: tempFilePaths })
        // 防止一次自定义相机多次点击拍照
        that.data.canTakePhoto = false
        // console.log('自定义相机：tempFilePaths: ', tempFilePaths)

        // iPhone拍出来的图片尺寸会过大，需要压缩
        if(!isIphone) {
          that.addWaterMark({ image: tempFilePaths, that, custom_camera_type, scene_id})
        } else {
          wx.compressImage({
            src: tempFilePaths, // 图片路径
            quality: 80, // 压缩质量
            success(res) {
              that.addWaterMark({ image: res.tempFilePath, that, custom_camera_type, scene_id})
            }
          })
        }
      },
      fail: function () {},
      complete: function () {}
    })
  },

  // 自定义相机拍摄图片加水印
  async addWaterMark({ image, that, custom_camera_type, scene_id }) {
    // 获取图片尺寸 动态设置canvas尺寸
    try {
      const res = await getImageInfo({ src: image })
      const { width=720, height=1080 } = res
      that.setData({
        canvas_size: {
          width,
          height
        }
      })
    } catch (e) {

    }
    const { width: canvas_width, height: canvas_height } = that.data.canvas_size
    console.log(JSON.stringify(that.data.canvas_size))
    const ctx = wx.createCanvasContext('mark-canvas')
    ctx.drawImage(image, 0, 0, canvas_width, canvas_height)
    // ctx.setFillStyle('#E95668')
    ctx.setFillStyle('#FF0000')
    ctx.setFontSize(20)
    // ctx.setTextAlign('left')
    // 获取水印文字内容
    const { store_name } = that.data.store_detail
    const { latitude, longitude } = that.data
    const now = new Date()

    const year = now.getFullYear(), month = that.addZero(now.getMonth()+1),
    day = that.addZero(now.getDate()), hour = that.addZero(now.getHours()), minute = that.addZero(now.getMinutes())
    ctx.fillText(`${store_name} (${latitude},${longitude}) ${year}/${month}/${day} ${hour}:${minute}`, 5, canvas_height - 5)
    ctx.draw(false, () => {
    // 从canvas导出image
      setTimeout(()=> {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: canvas_width,
          height: canvas_height,
          destWidth: canvas_width,
          destHeight: canvas_height,
          canvasId: 'mark-canvas',
          success(res) {
            console.log(res.tempFilePath)

            if(custom_camera_type === 'save') {
              wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success(res) {
                  wx.showToast({
                    title: '保存成功',
                    mask: true,
                    success() {
                      setTimeout(()=>{
                        that.setData({
                          openShelfCamera: false,
                          camera_image: null
                        })
                        that.data.canTakePhoto = true
                      }, 1000)
                    }
                  })
                  console.log('saveImageToPhotosAlbum res:', res)
                }
              })
            } else if (custom_camera_type === 'upload') {
              that.uploadImage({ tempFilePaths: res.tempFilePath, scene_id, that, isCamera:true, isLastImage: true  })
            }
          }
        })
      }, 500)
    })
  },

  addZero(str) {
    try {
      const num = parseInt(str)
      return num<10?'0'+num:num
    } catch (e) {
      return str
    }
  },

  async uploadImage({ tempFilePaths, scene_id, that, isCamera, isLastImage }) {

    if(isCamera) {
      that.setData({
        openShelfCamera: false,
        camera_image: null
      })
      that.data.canTakePhoto = true
    }

    // 在图片上传之前就将图片加到陈列中
    const { temp, image_url } = that.addLocalPhotoToScene({ tempFilePaths, scene_id, that })
    const { baseUrl } = that.data

    // try {
    //   const res = await uploadFile({
    //     url: baseUrl + "/qy/visit/image",
    //     name: "file",
    //     filePath: tempFilePaths,
    //     header: {
    //       "CorpId": app.globalData.corpid,
    //       "EmpId": app.globalData.empid,
    //       "UserId": app.globalData.userid,
    //       "Content-Type": "application/json",
    //     },
    //     formData: {
    //       "Role": '巡店员',
    //       "ImageType": '场景图片',
    //       "StoreId": that.data.storeId,
    //       'VisitId': that.data.visit_id,
    //       'SceneId': scene_id,
    //       "Longitude": that.data.longitude,
    //       "Latitude": that.data.latitude,
    //       "StoreLongitude": that.data.storeLongitude,
    //       "StoreLatitude": that.data.storeLatitude,
    //       "IsDetect": 'true',
    //     }
    //   })

    //   var my_res = JSON.parse(res.data);
    //   that.setData({
    //     isAbleSubmit: true
    //   })
    //   const current_img = my_res.data.image

    //   if (my_res.code === '200') {
    //     const { display_photograph, storeId } = that.data

    //     if(!temp) return
    //     // console.log('temp2: ', temp)
    //     that.setData({
    //       // openShelfCamera: false,
    //       // 使用临时图片路径 避免图片先显示后又需要加载
    //       [temp]: Object.assign({}, current_img, { image_url })
    //     })

    //     const timer = setInterval(() => {
    //       that.getSceneStatusById({ scene_id, that, baseUrl })
    //     }, 3000)
    //     // 定时器应该push进数组
    //     const { loadingtime=[] } = that.data
    //     loadingtime.push(timer)
    //     that.data.loadingtime = loadingtime
    //   }
    // } catch (e) {
    //   // util.hideLoading()
    //   wx.showToast({
    //     title: '请求超时',
    //     icon: 'none',
    //   })
    // }
  },

  addLocalPhotoToScene({ tempFilePaths, scene_id, that }) {
    const { scene_list=[] } = this.data.display_photograph
    let idx = -1, current_img_list = null
    for (let index in scene_list) {
      if(scene_list[index].scene_id == scene_id) {
        idx = index
        current_img_list = scene_list[index].img_list || []
        break
      }
    }
    if(idx < 0) return
    const temp = `display_photograph.scene_list[${idx}].img_list[${current_img_list.length}]`
    // console.log('temp: ', temp)
    that.setData({
      [temp]: {
        detect_status: '上传中',
        image_url: tempFilePaths,
        quality_status: null
      }
    })
    return { temp, image_url: tempFilePaths }
  },

  // [正式门店--门店拜访]从手机相册选择照片
  async chooseImageFromAlbum({ sceneItem, scene_id, that, hide }) {
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      async success(res) {
        hide()
        console.log('从相册选择：tempFilePaths: ', res.tempFilePaths)

        await Promise.all(
          res.tempFilePaths.map( async (item,index) => {
            return await that.uploadImage({
              tempFilePaths: res.tempFilePaths[index],
              scene_id, that,
              isCamera:false,
              isLastImage: index === res.tempFilePaths.length - 1
            })
          })
        )
      }
    })
  },

  // 图片删除
  deleteImg: function (e) {
    console.log(e.currentTarget.dataset)
    // var promo_id = e.currentTarget.dataset.promoindx
    var deleteIndex = e.currentTarget.dataset.index;
    var image_id = e.currentTarget.dataset.image_id
    if (e.currentTarget.dataset.type === '陈列拍照') {
      var scene_id = e.currentTarget.dataset.sceneid
    } else {
      var outside_index = e.currentTarget.dataset.outsideindex
      var inside_index = e.currentTarget.dataset.insideindex
    }

    var that = this;
    $wuxDialog().open({
      title: '确定要删除本张图片吗？',
      maskClosable: false,
      prefixCls: 'xdt',
      buttons: [{
              text: '取消',
          },
          {
              text: '确定',
              type: 'primary',
              onTap(e) {
                // if (image_id !== undefined) {
                if(true){
                  for (let j = 0; j < app.globalData.store_detail['display_photograph']['scene_list'].length; j++) {
                    if (app.globalData.store_detail['display_photograph']['scene_list'][j]['scene_id'] === scene_id) {
                      app.globalData.store_detail['display_photograph']['scene_list'][j]['img_list'].splice(deleteIndex, 1)
                    }
                  }
                  that.setData({
                    display_photograph: app.globalData.store_detail['display_photograph'],
                  })
                  console.log('img deleted', that.data.display_photograph)
                  // util.showLoading('加载中...')
                  // var baseUrl = wx.getStorageSync("config")
                  // wx.request({
                  //   url: baseUrl + "/qy/visit/image?ImageId=" + image_id,
                  //   method: "DELETE",
                  //   header: {
                  //     "CorpId": app.globalData.corpid,
                  //     "EmpId": app.globalData.empid,
                  //     "UserId": app.globalData.userid,
                  //   },
                  //   data: {},
                  //   success(res) {
                  //     util.hideLoading()
                  //     console.log("删除图片", res.data)
                  //     if (res.data.code == 200) {
                  //       for (let i = 0; i < app.globalData.store_detail.length; i++) {
                  //         if (app.globalData.store_detail[i]['store_id'] == app.globalData.store_id) {
                  //           for (let j = 0; j < app.globalData.store_detail[i]['display_photograph']['scene_list'].length; j++) {
                  //             if (app.globalData.store_detail[i]['display_photograph']['scene_list'][j]['scene_id'] === scene_id) {
                  //               app.globalData.store_detail[i]['display_photograph']['scene_list'][j]['img_list'].splice(deleteIndex, 1)
                  //             }
                  //           }

                  //           that.setData({
                  //             display_photograph: app.globalData.store_detail[i]['display_photograph'],
                  //           })
                  //           console.log('img deleted', that.data.display_photograph)
                  //         }
                  //       }

                  //       // 判断是否为【门店拜访】错误图片
                  //       console.log(that.data.errImgArr)
                  //       var curArr = that.data.errImgArr
                  //       for (let j = 0; j < that.data.errImgArr.length; j++) {
                  //         if (image_id == curArr[j]) {
                  //           curArr.splice(j, 1)
                  //           that.setData({
                  //             errImgArr: curArr
                  //           })
                  //           console.log(that.data.errImgArr)
                  //         }
                  //       }
                  //     } else {
                  //       console.log('err')
                  //     }
                  //   },
                  //   fail: function (e) {
                  //     util.hideLoading()
                  //     wx.showToast({
                  //       title: '请求超时',
                  //       icon: 'none',
                  //     })
                  //   },
                  // })
                }
              },
          },
      ],
    })
  },

  submitData() {
    const { scene_list=[] } = this.data.display_photograph
    let isAllqualified = true
    for(let i=0; i<scene_list.length; i++) {
      if(scene_list[i].img_list.filter(item => item.scene_type === '其他' || (item.quality_status && (item.is_blur || item.is_tilt))).length > 0) {
        isAllqualified = false
        break
      }
    }
    if(isAllqualified) {
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 1500
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    } else {
      $wuxDialog().open({
        // resetOnClose: true,
        title: '检测到有照片不合格',
        maskClosable: false,
        prefixCls: 'xdt',
        // content: '弹窗内容，告知当前状态、信息和解决方法，描述文字尽量控制在三行内',
        buttons: [{
                text: '重新拍摄',
            },
            {
                text: '仍然保存',
                type: 'primary',
                onTap(e) {
                  wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 1500
                  })
                  setTimeout(() => {
                    wx.navigateBack()
                  }, 1500)
                },
            },
        ],
      })
    }
  },

})